const fs = require('fs');
const path = require('path');
const moment = require('moment');

// 获取以当前日期命名的日志文件名，且以 .log 结尾
const getLogFileName = (date) => {
    return `log_${moment(date).format('YYYY-MM-DD')}.log`;
};

// 写入日志内容
const writeLog = (type = 0, logMessage = 0, user = 0, date = 0) => {
    let time = date ? date : new Date();
    logMessage = `${type}||${time}||${logMessage}||${user};;`
    
    let logDirectory = path.resolve(__dirname, '../../../../../../static');
    if (process.env.NODE_ENV == 'production') {
        logDirectory = path.resolve(__dirname, '../../static');
    }
    const logFile = path.join(logDirectory, getLogFileName(date ? date : new Date()));
    if (!fs.existsSync(logDirectory)) {
        fs.mkdirSync(logDirectory);
    }
    try {
        fs.appendFileSync(logFile, logMessage, 'utf-8');
    } catch (err) {
        console.error('创建或写入日志文件时出错:', err);
    }
};
function deleteFile() {
    try {
        let logDirectory = path.resolve(__dirname, '../../../../../../static');
        if (process.env.NODE_ENV == 'production') {
            logDirectory = path.resolve(__dirname, '../../static');
        }
        const files = fs.readdirSync(logDirectory);
        const logFiles = files.filter(file => file.endsWith('.log'));
        logFiles.forEach(logFile => {
            const filePath = path.join(logDirectory, logFile);
            try {
                fs.unlinkSync(filePath);
                console.log(`文件 ${filePath} 已成功删除`);
            } catch (err) {
                console.error(`删除文件 ${filePath} 时发生错误:`, err);
            }
        });
        return true
    } catch (error) {
        console.log(`output->error`, error)
        return false
    }
}

// 读取过去指定天数的日志内容
const readLogs = (days) => {
    let logDirectory = path.resolve(__dirname, '../../../../../../static');
    if (process.env.NODE_ENV == 'production') {
        logDirectory = path.resolve(__dirname, '../../static');
    }
    let allLogs = ''; // 存储所有日志内容
    const logFile = path.join(logDirectory, getLogFileName(days));
    if (fs.existsSync(logFile)) {
        try {
            const content = fs.readFileSync(logFile, 'utf-8');
            allLogs = content;
        } catch (err) {
            allLogs = ''
        }
    } else {
        allLogs = ''
    }
    return allLogs; // 返回读取到的所有日志内容
};

module.exports = {
    writeLog,
    deleteFile,
    readLogs,
};